<?php

namespace App\Jobs;

use App\Models\BrowseRecord;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;

class BrowseJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $ip;

    public $tries = 2;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($ip)
    {
        $this->ip = $ip;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //总浏览量
        Setting::query()->where('key', 'browse_count')->increment('count');

        //总访问量
        $redisIp = Redis::get('browse:ip:' . $this->ip);
        if (!$redisIp) {
            $endToday = mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y'));
            $time     = $endToday - time();
            Redis::setex('browse:ip:' . $this->ip, $time, $this->ip);

            $data = file_get_contents('http://ip.taobao.com/outGetIpInfo?ip=' . $this->ip . '&accessKey=alibaba-inc');

            $data = json_decode($data);

            if ($data->data) {
                $country = $data->data->country;
                $city    = $data->data->city;
                $region  = $data->data->region;
                $isp     = $data->data->isp;
            } else {
                $country = '未知';
                $city    = '未知';
                $region  = '未知';
                $isp     = '未知';
            }

            $ip                    = ip2long($this->ip);
            $browseRecord          = new BrowseRecord();
            $browseRecord->ip      = $ip;
            $browseRecord->country = $country;
            $browseRecord->city    = $city;
            $browseRecord->region  = $region;
            $browseRecord->isp     = $isp;
            $browseRecord->save();

            Setting::query()->where('key', 'access_count')->increment('count');
        }
    }
}
